﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Xml.Linq;

namespace ThreeByte.ActiveDeck.Service
{
    public class ByteBlock
    {
        public string BlockName { get; private set; }
        public string ContentHash { get; private set; }
        public byte[] Data { get; private set; }

        public ByteBlock(byte[] data, string blockName) {
            Data = data;

            //Calculate the BlockName
            BlockName = Convert.ToBase64String(Encoding.UTF8.GetBytes(blockName));
            
            //Calculate the Hash Code fields
            MD5 md5 = MD5.Create();
            md5.ComputeHash(Data);

            ContentHash = Convert.ToBase64String(md5.Hash);
        }

        public XElement ToXml() {
            XNamespace ns = ServiceConfiguration.NAMESPACE;
            XElement node = new XElement(ns + "ByteBlock", new XAttribute("Size", Data.Length));
            node.Value = Convert.ToBase64String(Data, Base64FormattingOptions.InsertLineBreaks);
            return node;
        }
    }
}
